<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Session;
use DB;
use Crypt;


class LoginController extends Controller
{
    //
    public function login(Request $request)
    {

        if($request -> isMethod('POST'))
        {  
            $isLogin = \Cookie::get('isLogin');
            if($isLogin)
            {
                $res = DB::table('admins') -> where('email',$isLogin) -> first(); 
                Session::put('admin',$res);
                return redirect('/admin/index') -> with(['info' => '登录成功']);
            }
            
            //闪存
            $request -> flashOnly('email');


            // 验证码匹配
            $code = $request -> input('code');
            if($code != Session::get('code'))
            {
                return back() -> with(['info' => '验证码错误']);
            }
            //验证邮箱和密码
            $email = $request -> input('email');
            $res = DB::table('admins') -> where('email',$email) -> first();
            if(!$res)
            {
                return back() -> with(['info' => '用户未注册']);
            }
            //解密
            $password = Crypt::decryptString($res -> password);
            if($request -> input('password') != $password )
            {
                return back() ->with(['info' => '用户或者密码错误']);
            }
            //判断是否记住我
            if($request -> has('checkMe'))
            {
               \Cookie::queue('isLogin',$res -> email,60 * 24 * 7);
            } 
            Session::put('admin',$res);
            return redirect('/admin/index') -> with(['info' => '登录成功']);
        }else
        {
            return view('admin.login.index',['title' => '登录']);
        }
       
    }

    public function logout()
    {
        Session::forget('admin');
        return redirect('/admin/login') -> with(['info' => '退出成功']);
    }
}
